package cn.dslcode.security.config.handler;

import cn.dslcode.common.web.WebUtil;
import cn.dslcode.common.web.response.RestResponse;
import cn.dslcode.security.common.CaptchaAuthenticationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dongsilin
 * @version 2018/4/8.
 *          登陆失败后的处理
 */
@Slf4j
@Component
public final class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("*******************AuthenticationFailureHandler");
        if (e instanceof CaptchaAuthenticationException) {
            WebUtil.output(response, RestResponse.buildFail(e.getMessage()), WebUtil.ResponseOutputType.JSON);
        } else if (e instanceof UsernameNotFoundException) {
            WebUtil.output(response, RestResponse.buildFail("用户名不存在"), WebUtil.ResponseOutputType.JSON);
        } else if (e instanceof BadCredentialsException) {
            WebUtil.output(response, RestResponse.buildFail("密码错误"), WebUtil.ResponseOutputType.JSON);
        } else {
            WebUtil.output(response, RestResponse.buildFail("操作失败"), WebUtil.ResponseOutputType.JSON);
        }
    }

}